<template>
  <a-form :model="formState" :rules="rules" :label-col="{span: 4}" ref="formRef">
    <a-form-item name="username" label="昵称">
      <a-input v-model:value="formState.username"/>
    </a-form-item>
    <a-form-item name="account" label="账号">
      <a-input v-model:value="formState.account"/>
    </a-form-item>
    <a-form-item name="password" label="密码">
      <a-input-password v-model:value="formState.password"/>
    </a-form-item>
    <a-form-item name="repeatPassword" label="确认密码">
      <a-input-password v-model:value="formState.repeatPassword"/>
    </a-form-item>
    <a-form-item name="avatar" label="头像" :wrapperCol="{span: 8}">
      <a-upload-dragger
          :style="{
              backgroundImage: `url(${avatarUrl})`,
              backgroundSize: '100%'
            }"
          accept="image/*"
          :showUploadList="false"
          :beforeUpload="avatarChange"
      >
        <p class="ant-upload-drag-icon">
          <PlusOutlined/>
        </p>
        <p class="ant-upload-text">点击或拖拽到此处上传头像</p>
      </a-upload-dragger>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import {computed, reactive, ref} from "vue";
import {PlusOutlined} from '@ant-design/icons-vue'
import type {FormInstance} from "ant-design-vue";
import {registerApi} from "@/apis/user";
import {message} from "ant-design-vue";

interface FormState {
  username: string;
  password: string;
  repeatPassword: string;
  avatar?: File;
  account: string;
}

const formRef = ref<FormInstance>();
const formState = reactive<FormState>({
  username: '',
  password: '',
  repeatPassword: '',
  avatar: undefined,
  account: ''
})
const rules = {
  username: [{required: true, message: '请输入用户昵称'}],
  password: [{required: true, message: '请输入密码'}],
  repeatPassword: [
    {required: true, message: '请重新输入密码'}, {
      validator(r: any, v: string) {
        if(v !== formState.password) return Promise.reject('两次输入的密码不一致')
        return Promise.resolve()
      },
      trigger: 'change'
    }],
  avatar: [{required: true, message: '请上传头像'}],
  account: [{required: true, message: '请输入账号'}],
}

const avatarChange = (file: File) => {
  formState.avatar = file;
  return false;
}

const avatarUrl = computed(() => formState.avatar instanceof File ? URL.createObjectURL(formState.avatar) : '');

const commit = async () => {
  const data = await formRef.value?.validate()
  await registerApi(data)
  message.success('注册成功');
}

defineExpose({commit});
</script>

<style scoped>

</style>